package com.jzy.gulimall.search.service.impl;

import cn.hutool.json.JSONUtil;
import com.jzy.common.to.es.SkuEsTo;
import com.jzy.gulimall.search.config.ElasticSearchConfig;
import com.jzy.gulimall.search.constant.EsConstant;
import com.jzy.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author jzy
 * @date 2020/9/11 18:14
 */
@Service
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    /**
     * spu管理 上架 更新es库
     */
    @Override
    public boolean productStateUp(List<SkuEsTo> skuEsTos) throws IOException {
        BulkRequest bulkRequest = new BulkRequest(EsConstant.PRODUCT_INDEX);
        skuEsTos.forEach(item -> {
            IndexRequest indexRequest = new IndexRequest();
            indexRequest.id(String.valueOf(item.getSkuId()));
            indexRequest.source(JSONUtil.toJsonStr(item), XContentType.JSON);
            bulkRequest.add(indexRequest);
        });
        //BulkRequest bulkRequest, RequestOptions options
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);
        // TODO: 2020/9/12 更新索引库错误处理
        boolean b = bulk.hasFailures();
        List<String> collect = Arrays.stream(bulk.getItems()).map(BulkItemResponse::getId).collect(Collectors.toList());
        log.info("上架成功:{}", collect);
        return b;
    }
}